package com.server.server_a10.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.server_a10.entity.Inf.HeaterIdInf;
import com.server.server_a10.entity.Inf.LightIdInf;
import com.server.server_a10.entity.Inform;
import com.server.server_a10.mapper.HeaterMapper;
import com.server.server_a10.mapper.HomeMapper;
import com.server.server_a10.mapper.LightMapper;
import com.server.server_a10.mqttServer.MqttGateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class EquipmentOnOrOff {

    @Resource
    private MqttGateway mqttGateway;
    @Autowired
    HeaterMapper heaterMapper;

    @Autowired
    LightMapper lightMapper;
    @Autowired
    HomeMapper homeMapper;

    //一键关闭所有
    @PostMapping(value = "/close")
    public Inform close() {
        Inform inform = new Inform();


        return inform;
    }

    //一键控制房子内所有的灯
    @PostMapping(value = "/controllerAllLightIdByHomeId")
    public Inform controllerAllLithtByHomeId(@RequestBody Map<String, Object> request) {
        int id = (int) request.get("id");
        int isOpen = (int) request.get("isOpen");
        Inform inform = new Inform();

        if (isOpen!=1 && isOpen!=0){
            inform.fail("信息格式错误",null);
            return inform;
        }

        List<Integer> rooms = homeMapper.selRoomByHomeId(id);

        for (int roomId : rooms) {
            List<LightIdInf> idInfs = lightMapper.getAllLightIdByHomeIdOrRoomId(roomId, "room_id");

            if (!controllerLightByIdList(idInfs, isOpen)) {
                inform.fail("未能完全执行操作！！！", null);
                return inform;
            }

        }
        inform.success("操作完成",rooms);
        return inform;
    }

    //一键控制房间内所有的灯
    @PostMapping(value = "/controllerAllLightIdByRoomId")
    public Inform controllerAllLithtByRoomId(@RequestBody Map<String, Object> request) {
        int id = (int) request.get("id");
        int isOpen = (int) request.get("isOpen");
        Inform inform = new Inform();

        if (isOpen!=1&&isOpen!=0){
            inform.fail("信息格式错误",null);
            return inform;
        }

        List<LightIdInf> idInfs = lightMapper.getAllLightIdByHomeIdOrRoomId(id, "room_id");

        if (idInfs.isEmpty()) {
            inform.isNull("没有获取到任何的数据");
        } else {
            if (controllerLightByIdList(idInfs, isOpen)) {
                inform.success("操作成功", idInfs);
            } else {
                inform.fail("操作失败", null);
            }
        }

        return inform;
    }


    //开关房子内所有的空调
    @PostMapping(value = "/controllerAllHeaterIdByHomeId")
    public Inform controllerAllHeaterByHomeId(@RequestBody Map<String, Object> request) {
        int id = (int) request.get("id");
        int isOpen = (int) request.get("isOpen");
        Inform inform = new Inform();

        if (isOpen!=1&&isOpen!=0){
            inform.fail("信息格式错误",null);
            return inform;
        }

        List<HeaterIdInf> idInfs = heaterMapper.getAllHeaterIdByHomeIdOrRoomId(id, "home_id");
        if (idInfs.isEmpty()) {
            inform.isNull("没有获取到任何的数据");
        } else {
            if (controllerHeaterByIdList(idInfs, isOpen)) {
                inform.success("操作成功", idInfs);
            } else {
                inform.fail("操作失败", null);
            }
        }
        return inform;
    }

    //开关房间内所有的空调
    @PostMapping(value = "/controllerAllHeaterIdByRoomId")
    public Inform controllerAllHeaterByRoomId(@RequestBody Map<String, Object> request) {
        int id = (int) request.get("id");
        int isOpen = (int) request.get("isOpen");
        Inform inform = new Inform();

        if (isOpen!=1&&isOpen!=0){
            inform.fail("信息格式错误",null);
            return inform;
        }

        List<HeaterIdInf> idInfs = heaterMapper.getAllHeaterIdByHomeIdOrRoomId(id, "room_id");
        if (idInfs.isEmpty()) {
            inform.isNull("没有获取到任何的数据");
        } else {
            if (controllerHeaterByIdList(idInfs, isOpen)) {
                inform.success("操作成功", idInfs);
            } else {
                inform.fail("操作失败", null);
            }
        }
        return inform;
    }


    /*
    控制全部的空调
    入参为空调list和isOpen。
            list存放需要控制的空调参数（list中包涵homeId和roomId和HeaterId），
            isOpen为1表示开，为0表示关
     */
    private boolean controllerHeaterByIdList(List<HeaterIdInf> list, int isOpen) {
        boolean isOk = true;
        ObjectMapper objectMapper = new ObjectMapper();

        for (HeaterIdInf heaterIdInf : list) {
            int homeId = heaterIdInf.getHomeId();
            int roomId = heaterIdInf.getRoomId();
            int heaterId = heaterIdInf.getHeaterId();

            String topic = homeId + "/" + roomId + "/heater";

            Map<String, Object> push = new HashMap() {{
                put("type", "heater");
                put("id", heaterId);
                put("isOpen", isOpen);
                put("model", 0);
                put("temperature", 17);
                put("airSpeed", 0);
            }};
//            String pushJson = JSON.toJSONString(push);
            //send mqtt
            try {
                mqttGateway.sendToMqtt(topic, 1, objectMapper.writeValueAsString(push));
            } catch (JsonProcessingException e) {
                isOk = false;
                throw new RuntimeException(e);
            }

        }

        return isOk;
    }

    /*
    控制房间内全部的灯
    入参为灯list和isOpen。
            list存放需要控制的空调参数（list中包涵homeId和roomId和LightId），
            isOpen为1表示开，为0表示关
     */
    private boolean controllerLightByIdList(List<LightIdInf> list, int isOpen) {
        boolean isOk = true;
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Integer>> content = new ArrayList<>();
        int homeId = 0;
        int roomId = 0;

        for (LightIdInf lightIdInf : list) {
            homeId = lightIdInf.getHomeId();
            roomId = lightIdInf.getRoomId();
            int heaterId = lightIdInf.getLightId();
            content.add(new HashMap() {{
                put("id", heaterId);
                put("isOpen", isOpen);
            }});
        }


        String topic = homeId + "/" + roomId + "/light";

        Map<String, Object> push = new HashMap() {{
            put("type", "light");
            put("list", content);
        }};
//        String pushJson = JSON.toJSONString(push);
        //send mqtt
        try {
            mqttGateway.sendToMqtt(topic, 1, objectMapper.writeValueAsString(push));
        } catch (JsonProcessingException e) {
            isOk = false;
            throw new RuntimeException(e);
        }

        return isOk;
    }
}
